/* eslint-disable @typescript-eslint/no-explicit-any */
import userConfigStore from '@renderer/store/userConfigStore'
import { mainProgressNoticeType, VideoState, VideoType } from '@renderer/type'
import { ElMessage } from 'element-plus'
import { ref, toRefs } from 'vue'

export default () => {
  const isRun = ref(false)
  const { config } = userConfigStore()
  const video = ref<VideoType>()
  const { files, videoSaveDirectory } = toRefs(config)

  // 处理前验证
  const validate = () => {
    let message = ''
    console.log(videoSaveDirectory.value)
    if (videoSaveDirectory.value.trim() === '') message = '请配置目录文件？'
    if (files.value.length === 0) message = '请选择视频文件？'
    if (!video.value) message = '视频压缩完毕！'
    if (message) ElMessage.warning({ message, grouping: true })
    return message === ''
  }

  // 获取压缩文件
  const getCompressFile = () => {
    video.value = config.files.find((video) => video.state === VideoState.READY)
    if (video.value) video.value.state = VideoState.COMPRESS
    else isRun.value = false
    // ElMessage.success('没有可压缩视频？')
  }
  // 进度通知事件
  const progressNotice = () => {
    // window.api.progressNotice((progress: number) => {
    //   video.value!.progress = progress
    // })
    window.api.mainProgressNotice((type: mainProgressNoticeType, options: any) => {
      switch (type) {
        case mainProgressNoticeType.PROGRESS:
          video.value!.progress = options
          break
        case mainProgressNoticeType.END:
          video.value!.state = VideoState.FINISH
          compress()
          break
        case mainProgressNoticeType.DIRECTORYCHECK:
          ElMessage.warning({ grouping: true, message: '视频目录不存在！' })
          video.value!.state = VideoState.READY
          isRun.value = false
          break
        case mainProgressNoticeType.FILE_IS_EXISTS:
          video.value!.state = VideoState.ERROR
          compress()
          // ElMessage.warning({ grouping: true, message: '文件已存在！' })
          // isRun.value = false
          break
        case mainProgressNoticeType.STOP:
          ElMessage.warning({ grouping: true, message: '停止转码了' })
          isRun.value = false
          break
      }
    })
  }

  const run = () => {
    if (isRun.value) return
    isRun.value = true
    compress()
  }

  // 压缩
  const compress = () => {
    getCompressFile()
    if (validate() === false) return
    isRun.value = true
    window.api.compress({
      file: { ...video.value! },
      fps: Number(config.frame),
      size: config.size,
      saveDirectory: config.videoSaveDirectory
    })
  }

  return { run, isRun, progressNotice }
}
